package com.dongnao.network.bio;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author sjy
 * @date 2024年05月09日 16:16
 */
public class DatagramServer {

    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(20000); // 监听指定端口
        while (true) {
            // 接收客户端的数据
            byte[] buffer = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
            System.out.println("服务器等待接收数据");
            socket.receive(packet); // 收取一个UDP数据包
            System.out.println("客户端响应：");
            System.out.println("数据：" + new String(packet.getData()) + " 偏移量" + packet.getOffset() + " 长度" + packet.getLength());

            // 发送数据给客户端
            byte[] data = "你好我是服务器，谢谢你的连接".getBytes();
            InetAddress address = packet.getAddress();
            int port = packet.getPort();
            DatagramPacket packet2 = new DatagramPacket(data, data.length, address, port);
            socket.send(packet2);//发送UDP数据包
        }
    }
}
